package com.cssy.yd.logic.web;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.alibaba.fastjson.JSONArray;
import com.cssy.authority.service.IScDepartmentService;
import com.cssy.authority.service.IScUserRolewhPlaceService;
import com.cssy.base.web.BaseController;
import com.cssy.base.web.BodyMsg;
import com.cssy.yd.basic.service.IBasicCompanyService;


import com.cssy.yd.logic.entity.LogicSoReturnItemBatchDO;
import com.cssy.yd.logic.entity.LogicSoReturnItemDO;
import com.cssy.yd.logic.entity.LogicSoWareItemBatchDO;
import com.cssy.yd.logic.entity.LogicSoWareItemFreezedealbatchDO;
import com.cssy.yd.logic.entity.LogicSoWarefreezeDO;
import com.cssy.yd.logic.entity.LogicSoWarefreezeItemDO;
import com.cssy.yd.logic.entity.LogicSoWarefreezedealDO;
import com.cssy.yd.logic.entity.LogicSoWarefreezedealItemBatchDO;
import com.cssy.yd.logic.entity.LogicSoWarefreezedealItemDO;
import com.cssy.yd.logic.entity.LogicSoWareunfreezeDO;
import com.cssy.yd.logic.entity.LogicSoWareunfreezeItemBatchDO;
import com.cssy.yd.logic.entity.LogicSoWareunfreezeItemDO;

import com.cssy.yd.logic.service.ILogicSoItemService;
import com.cssy.yd.logic.service.ILogicSoService;
import com.cssy.yd.logic.service.ILogicSoWarefreezeService;
import com.cssy.yd.logic.service.ILogicSoWarefreezedealService;
import com.cssy.yd.logic.service.ILogicSoWareunfreezeService;
import com.plat.helper.JqGridHandler;
import com.plat.helper.SearchCondition;
import com.plat.helper.SearchConditions;
import com.plat.helper.SearchResult;
import com.plat.util.GlobalResLoader;
import com.plat.util.OperationFlag;
import com.plat.util.SessionUtil;
import com.plat.util.json.OutJsonGrid;

/**
 * 销售解冻控制器
 * @author huang.xuming [2013-8-23]
 *
 */
@Controller
@RequestMapping("/yd/logic/sowareunfreeze")
public class SoWareUnfreezeController extends BaseController<LogicSoWareunfreezeDO> {

	private static final Logger logger = Logger.getLogger(SoWareUnfreezeController.class);
			
	private static final String MANAGER = "/yd/logic/sowareunfreeze/SoWareUnfreezeManager";// 列表页面
	private static final String EIDT = "/yd/logic/sowareunfreeze/SoWareUnfreezeOperation";// 添加、修改、显示页面
	private static final String ITEMMANAGER = "/yd/logic/sowareunfreeze/ItemManager";// 添加、修改、显示页面
	
	
	@Resource(name = "basicCompanyService")
	IBasicCompanyService basicCompanyService;
	@Resource(name="scUserRolePlaceService")
	private IScUserRolewhPlaceService scUserRolePlaceService;
	
	@Resource(name = "logicSoService")
	private ILogicSoService logicSoService;
	
	@Resource(name = "logicSoItemService")
	private ILogicSoItemService logicSoItemService;
	
	@Resource(name = "logicSoWarefreezeService")
	private ILogicSoWarefreezeService logicSoWarefreezeService ;
	
	@Resource(name = "logicSoWareunfreezeService")
	private ILogicSoWareunfreezeService logicSoWareunfreezeService ;
	
	@Resource(name = "logicSoWarefreezedealService")
	private ILogicSoWarefreezedealService logicSoWarefreezedealService ;
	
	@Resource(name = "scDepartmentService")
    private IScDepartmentService scDepartmentService;
	
	
	@Override
	public String manager(HttpServletRequest request, Model model)
			throws Exception {
		return MANAGER;
	}
	@RequestMapping(value="itemManager")
	public String itemManager(HttpServletRequest request, Model model)
			throws Exception {
		String itemdata =request.getParameter("data");
		String billstatus =request.getParameter("billstatus");
		String updstatus =request.getParameter("updstatus");
		LogicSoWareunfreezeItemDO unItemDO=JSONArray.parseObject(new String(itemdata.getBytes("ISO-8859-1"),"UTF-8"), LogicSoWareunfreezeItemDO.class);
		if(unItemDO.getItemBatch() != null & !"".equals(unItemDO.getItemBatch())){
			request.setAttribute("itemBatch", unItemDO.getItemBatch());
		}
		request.setAttribute("updstatus", updstatus);
		request.setAttribute("billstatus", billstatus);
		return ITEMMANAGER;
	}
	@Override
	public void list(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		JqGridHandler hander = new JqGridHandler(request);
		SearchConditions scs = new SearchConditions();
		hander.getWheres(scs);
		SearchResult result = logicSoWareunfreezeService.findListByExample(scs);
		OutJsonGrid out = new OutJsonGrid(result);
		out.printJSon(response);
	}
	@RequestMapping(value = "/itemlist")
	public void itemlist(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String itembatch =request.getParameter("itembatch");
		String updstatus = request.getParameter("updstatus");
		SearchResult result= new SearchResult();
		List<LogicSoWareunfreezeItemBatchDO> batchDOs = new ArrayList<LogicSoWareunfreezeItemBatchDO>();
		if("1".equals(updstatus)){
			if(itembatch != null  && !"".equals(itembatch)){
				batchDOs=JSONArray.parseArray(new String(itembatch.getBytes("ISO-8859-1"),"UTF-8"), LogicSoWareunfreezeItemBatchDO.class);
			}
		}else{
			if(itembatch != null  && !"".equals(itembatch)){
					 List<LogicSoWarefreezedealItemBatchDO> itemBatchDOs=JSONArray.parseArray(new String(itembatch.getBytes("ISO-8859-1"),"UTF-8"), LogicSoWarefreezedealItemBatchDO.class);
					 LogicSoWareunfreezeItemBatchDO unItemBatchDO = null;
						if(itemBatchDOs != null && itemBatchDOs.size() > 0){
							for (LogicSoWarefreezedealItemBatchDO batchDO : itemBatchDOs) {
								unItemBatchDO = new LogicSoWareunfreezeItemBatchDO();
								unItemBatchDO.setMaterialsid(batchDO.getMaterialsid());
								unItemBatchDO.setProdNo(batchDO.getProdNo());
								unItemBatchDO.setProdName(batchDO.getProdName());
								unItemBatchDO.setProdSpecDesc(batchDO.getProdSpecDesc());
								unItemBatchDO.setProdBatch(batchDO.getProdBatch());
								unItemBatchDO.setProdBUnit(batchDO.getProdBUnit());
								unItemBatchDO.setStatus(batchDO.getStatus());
								unItemBatchDO.setProdUnit(batchDO.getProdUnit());
								unItemBatchDO.setProdUnitConvert(batchDO.getProdUnitConvert());
								unItemBatchDO.setDjBQuantity(batchDO.getDjBQuantity());
								unItemBatchDO.setDjQuantity(batchDO.getDjQuantity());
								unItemBatchDO.setDjckQuantity(batchDO.getCkQuantity());
								unItemBatchDO.setDjckBQuantity(batchDO.getCkBQuantity());
								unItemBatchDO.setDjjdBQuantity(batchDO.getDjjdBQuantity());
								unItemBatchDO.setDjjdQuantity(batchDO.getDjjdQuantity());
								batchDOs.add(unItemBatchDO);
							}
						}
			}
		}
			result.setRecordCount(batchDOs.size());
			result.setResults(batchDOs);
	
			 OutJsonGrid out=new OutJsonGrid(result);
			 out.printJSon(response);
		}
	@Override
	public String operationForm(HttpServletRequest request, 
			@PathVariable String id,@PathVariable String flag, Model model) throws Exception {
		
		if (OperationFlag.ADD.equals(flag)) {
			// 新增加时操作
			model.addAttribute("flag", "ADD");
		} else {
			LogicSoWareunfreezeDO sowarefreeze = logicSoWareunfreezeService.findListById(id);
			//List<LogicSoWareunfreezeItemDO> sowareitem = logicSoWareunfreezeService.findItemListBysowareunfreezeId(sowarefreeze.getId());
			model.addAttribute("flag", "EDIT");
			model.addAttribute("sowareunfreeze", sowarefreeze);
			//model.addAttribute("sowareunfreezeitem", sowareitem);
		}
		
//		//可解冻的销售订单//不可行，不知道仓库等信息
//		List<LogicSoDO> solist = new ArrayList<LogicSoDO>();
//		SearchConditions scsso = new SearchConditions();
//		scsso.addCondition("billstatus", "4,5", SearchCondition.OP_IN);// 订单状态-二审完结、三审完结
//		scsso.addCondition("ware_status", "2", SearchCondition.OP_NOTEQUAL);// 出库状态-非完全出库
//		scsso.addCondition("frozen_status", "1,2,3", SearchCondition.OP_IN);// 订单库存冻结
//		scsso.setLimitPage(false);// 不分页
//		solist = logicSoService.findListByExample(scsso).getResults();
		
		//可解冻的冻结申请单
		List<LogicSoWarefreezeDO> solist = new ArrayList<LogicSoWarefreezeDO>();
		SearchConditions scsso = new SearchConditions();
		scsso.addCondition("billstatus", "2", SearchCondition.OP_EQUAL);// 订单状态-二审完结、三审完结
		scsso.addCondition("frozen_status", "1,2,3", SearchCondition.OP_IN);// 订单库存冻结
		scsso.setLimitPage(false);// 不分页
		solist = logicSoWarefreezeService.findListByExample(scsso).getResults();
				
		model.addAttribute("solist", solist);
		
		//部门列表
		model.addAttribute("depts",SoController.getDepartmentList(scDepartmentService));
				
		return EIDT;
	}

	@RequestMapping(value = "/griditems")
	public void griditems(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String id = request.getParameter("id");
		if(StringUtils.isNotBlank(id)){
			LogicSoWareunfreezeDO sowarefreeze = logicSoWareunfreezeService.findListById(id);
			List<LogicSoWareunfreezeItemDO> sowareitem = logicSoWareunfreezeService.findItemListBysowareunfreezeId(sowarefreeze.getId());
			OutJsonGrid out = new OutJsonGrid(sowareitem);
			out.printJSon(response);
		}
	}
	
	@Override
	public Map<String, Object> save(HttpServletRequest request,
			LogicSoWareunfreezeDO curAP, BindingResult result, Model model)
			throws Exception {
		BodyMsg bodyMap = BodyMsg.getInstance();
		String itemdata =request.getParameter("itemdata");
		if(itemdata==null&&"".equals(itemdata)){
			bodyMap.isFail();
			bodyMap.configWebInfor("物料内容不能为空！");
			return bodyMap.modelMap;
		}try {
			logicSoWareunfreezeService.soWareunfreezeSave(request, curAP);
			bodyMap.isSuccess();
			bodyMap.configWebInfor(GlobalResLoader.getOpsuccess());
			bodyMap.configWebId(curAP.getId());
		} catch (Exception e) {
			logger.warn(e.getMessage(),e);
			bodyMap.isFail();
			bodyMap.configWebInfor(GlobalResLoader.getOpfailed()+ e.getMessage());
		}
		return bodyMap.modelMap;
	}

	@Override
	public Map<String, Object> delete(HttpServletRequest request,
			HttpServletResponse response, Model model) throws Exception {
		BodyMsg bodyMap = BodyMsg.getInstance();
		try {
			String ids = request.getParameter("ids");
			String[] fields=ids.split(",");
			for(String field : fields){
				LogicSoWareunfreezeDO ld=logicSoWareunfreezeService.findListById(field);
				ld.setRemoved(1);
				logicSoWareunfreezeService.updateToDelete(ld, SessionUtil.getUser(request));
			}
			bodyMap.isSuccess(GlobalResLoader.getOpsuccess());
		} catch (Exception e) {
			logger.warn(e.getMessage(),e);
			bodyMap.isFail(GlobalResLoader.getOpfailed() + e.getMessage());
		}
		return bodyMap.modelMap;
	}
	
	/**
	 * 根据销售冻结申请编码，获取包含的冻结处理单
	 * @param sowarefreezeNo
	 * @param request
	 * @param response
	 */
	@RequestMapping("/sowarefreezedeallist")
	public void sowarefreezedeallist(@RequestParam("sowarefreezeNo") String sowarefreezeNo, HttpServletRequest request, HttpServletResponse response){
		SearchResult result= new SearchResult();
		
		List<LogicSoWarefreezedealDO> soitemlist = new ArrayList<LogicSoWarefreezedealDO>();
		if(StringUtils.isNotBlank(sowarefreezeNo)){
			SearchConditions scs = new SearchConditions();
			scs.addCondition("sowarefreeze_no", sowarefreezeNo, SearchCondition.OP_EQUAL);
			scs.addCondition("billstatus", "2", SearchCondition.OP_EQUAL);//单据标记
			scs.addCondition("unfrozen_status", "0,1", SearchCondition.OP_IN);//解冻标记
			soitemlist = logicSoWarefreezedealService.findListByExample(scs).getResults();
		}
		
		result.setResults(soitemlist);
		result.setRecordCount(soitemlist.size());
		OutJsonGrid out = new OutJsonGrid(result);
		out.printJSon(response);
	}
	
	/**
	 * 根据冻结申请ID获取相应item
	 * @param sowarefreezeId
	 * @param request
	 * @param response
	 */
	@RequestMapping("/sowarefreezeitemlist")
	public void sowarefreezeitemlist(@RequestParam("sowarefreezeId") String sowarefreezeId, HttpServletRequest request, HttpServletResponse response){
		SearchResult result= new SearchResult();
		
		List<LogicSoWarefreezeItemDO> soitemlist = new ArrayList<LogicSoWarefreezeItemDO>();
		if(StringUtils.isNotBlank(sowarefreezeId)){
			soitemlist = logicSoWarefreezeService.findItemListBysowarefreezeId(sowarefreezeId);
		}
		
		result.setResults(soitemlist);
		result.setRecordCount(soitemlist.size());
		OutJsonGrid out = new OutJsonGrid(result);
		out.printJSon(response);
	}
	
	/**
	 * 根据冻结处理单ID获取相应item
	 * @param sowarefreezedealId
	 * @param request
	 * @param response
	 */
	@RequestMapping("/sowarefreezedealitemlist")
	public void sowarefreezedealitemlist(@RequestParam("sowarefreezedealId") String sowarefreezedealId, HttpServletRequest request, HttpServletResponse response){
		SearchResult result= new SearchResult();
		
		List<LogicSoWarefreezedealItemDO> soitemlist = new ArrayList<LogicSoWarefreezedealItemDO>();
		if(StringUtils.isNotBlank(sowarefreezedealId)){
			soitemlist = logicSoWarefreezedealService.findItemListBysowfdId(sowarefreezedealId);
		}
		if(soitemlist!=null){
			for (LogicSoWarefreezedealItemDO logicSoWarefreezedealItemDO : soitemlist) {
				logicSoWarefreezedealItemDO.setVal(null);
			}
		}
		result.setResults(soitemlist);
		result.setRecordCount(soitemlist.size());
		OutJsonGrid out = new OutJsonGrid(result);
		out.printJSon(response);
	}
	
	
	
	@RequestMapping(value = "/exportExcel")
	public void printer(HttpServletRequest request, HttpServletResponse response) throws Exception{
		//TODO 导出功能
//		try {
//			
//			
//			String id = request.getParameter("id");
//			LogicSoWareDO soware=new LogicSoWareDO();
//			List<LogicSoWareItemDO> lp=new ArrayList<LogicSoWareItemDO>();
//			List<LogicFreightageDO> freightageDOs=new ArrayList<LogicFreightageDO>();
//			if(!"".equals(id)&&id!=null){
//				soware = logicSoWareService.findListById(id);
//			}
//			if(soware.getId()!=null){
//				lp = logicSoWareItemService.findItemListBysowareId(soware.getId());
//				SearchConditions sc = new SearchConditions();
//				sc.setRemovedProperty(null);//判断是否有删除标识
//				sc.addCondition("tid", soware.getId(), SearchCondition.OP_EQUAL);
//				freightageDOs=logicFreightageService.findListByExample(sc).getResults();
//			}
//			if(lp.size()>0){
//				request.setAttribute("soware", soware);
//				request.setAttribute("lp", lp);
//				request.setAttribute("row", lp.size());
//				if(freightageDOs.size()>0){
//					for(int i=0;i<freightageDOs.size();i++){
//						if("铁运费".equals(freightageDOs.get(i).getFreightagename())){
//							request.setAttribute("T", freightageDOs.get(i).getFreightageprice());
//						}
//						if("海运费".equals(freightageDOs.get(i).getFreightagename())){
//							request.setAttribute("H", freightageDOs.get(i).getFreightageprice());
//						}
//						if("短运费".equals(freightageDOs.get(i).getFreightagename())){
//							request.setAttribute("D", freightageDOs.get(i).getFreightageprice());
//						}
//						if("装卸费".equals(freightageDOs.get(i).getFreightagename())){
//							request.setAttribute("Z", freightageDOs.get(i).getFreightageprice());
//						}
//						if("落箱费".equals(freightageDOs.get(i).getFreightagename())){
//							request.setAttribute("L", freightageDOs.get(i).getFreightageprice());
//						}
//						if("其他".equals(freightageDOs.get(i).getFreightagename())){
//							request.setAttribute("Q", freightageDOs.get(i).getFreightageprice());
//						}
//					}
//					
//				}
//				
//				response.setContentType("application/vnd.ms-excel");
//				response.setHeader("Content-disposition", "attachment;filename=export_" + System.currentTimeMillis() + ".xls");
//			
//				RequestDispatcher dispatcher = request.getRequestDispatcher("/views/printer/SoWarePrint.jsp");
//			
//				dispatcher.forward(request, response);
//			}
//		} catch (ServletException e) {
//			e.printStackTrace();
//		}
	}
	
}
